//
//  CRMSearchShopCarListVC.m
//  New_Runway
//
//  Created by NewLife on 2018/3/8.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CRMSearchShopCarListVC.h"
#import "NRWCarListsModel.h"
#import "NRWCarChooseBrandVC.h"
#import "NRWCarChooseCarModelVC.h"
#import "NRWCarMultipleChooseCarCell.h"

@interface CRMSearchShopCarListVC ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation CRMSearchShopCarListVC
{
    UIButton *chooseBrandBtn;
    UIButton *chooseCarBtn;
    UITableView *tableView;
    
    NRWCarListsModel *model;
    
    NSString *_brandId;
    NSString *_modelId;
//    NSString *_seriesId;
    
    NSInteger pageIndex;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.titleLabel.text = @"意向车辆";
    [self.navigationBarView setupRightItemTitle:@"确定"];
    
    [self setupTopView];
    
    [self setupView];
    
    [self loadNewData];
}

- (void)rightItemClick {
    
    UIViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
    
    if ([vc isKindOfClass:NSClassFromString(@"NRWCarAddIntentionVC")]) {
        
        [vc setValue:self.selectCarModelArrM.copy forKey:@"selecCarModelArr"];
        [vc setValue:self.selectCarIdArrM forKey:@"selectCarIdArrM"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)setupTopView {
    
    UIView *topView = DPView().setBackgroundColor([UIColor whiteColor])
    .setFrame(CGRectMake(0, self.navH, Screen_width, 40));
    
    chooseBrandBtn = DPLayoutButton(5, DPBtnLayoutTypeLeftTitleRightImage)
    .setTitleFont(kPingFangRegular13())
    .setNormalTitleColor(getColorFromString(@"323232"))
    .setNormalImage(getImageFromName(@"triangle"))
    .addClickAction(self, @selector(chooseBrandBtnDidClick:))
    .setNormalTitle(@"品牌");
    
    chooseCarBtn = DPLayoutButton(5, DPBtnLayoutTypeLeftTitleRightImage)
    .setTitleFont(kPingFangRegular13())
    .setNormalTitleColor(getColorFromString(@"323232"))
    .setNormalImage(getImageFromName(@"triangle"))
    .addClickAction(self, @selector(chooseCarBtnDidClick:))
    .setNormalTitle(@"车系");
    
    topView.addSubview(chooseBrandBtn).addSubview(chooseCarBtn);
    self.view.addSubview(topView);
    
    [chooseBrandBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(topView);
        make.left.equalTo(topView.mas_left).offset(15);
    }];
    
    [chooseCarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(topView);
        make.right.equalTo(topView.mas_right).offset(-15);
    }];
}

- (void)setupView{
    
    tableView = DPTableViewForStyle(UITableViewStylePlain)
    .setFrame(CGRectMake(0, self.navH + 40, Screen_width, Screen_height - self.navH - 40))
    .setSeparatorStyle(UITableViewCellSeparatorStyleNone)
    .setDelegate(self)
    .setDataSource(self)
    .registerCell(NRWCarMultipleChooseCarCell.class, @"cell");
    
    self.view.addSubview(tableView);
    
    [tableView addHeaderRefreshWithTarget:self action:@selector(loadNewData)];
    [tableView addFooterRefreshWithTarget:self action:@selector(loadMoreData)];

}

- (void)loadNewData {
    
    pageIndex = 1;
    
    [self loadCarListData];
}

- (void)loadMoreData {
    
    pageIndex++;
    
    [self loadCarListData];
}

- (void)loadCarListData {
    
    NSMutableDictionary *dictM = @{}.mutableCopy;
    
    NSString *shopId = [NRWCarUser sharedUser].shopId;
    NSString *marketId = [NRWCarUser sharedUser].marketId;
    
    [dictM setObject:shopId forKey:@"shopId"];
    [dictM setObject:marketId forKey:@"marketId"];
    [dictM setObject:@(pageIndex) forKey:@"pageIndex"];
    [dictM setObject:@15 forKey:@"pageSize"];
    
    if (!isEmptyOrNilString(_brandId)) {
        [dictM setObject:_brandId forKey:@"brandId"];
    }
    
    if (!isEmptyOrNilString(_modelId)) {
        [dictM setObject:_modelId forKey:@"modelId"];
    }
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",CRMContextApi,crmIntentionCars] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        
        NRWCarListsModel *listModel = [NRWCarListsModel mj_objectWithKeyValues:response];
        
        if (listModel.code == 1) {
            
            if (pageIndex == 1) {
                
                if (listModel.result.count == 0) {
                    
                    [tableView addDefaultViewWithText:@"没找到相关车辆" defaultImageType:DefaultImageTypeNoData];
                    model = nil;
                } else {
                    
                    [tableView removeDefaultView];
                    model = listModel;
                }
            } else {
                
                NSMutableArray *arrM = [NSMutableArray arrayWithArray:model.result];
                [arrM addObjectsFromArray:listModel.result];
                listModel.result = arrM.copy;
                model = listModel;
            }
            [tableView reloadData];
        }
        
        [tableView endRefresh];
        [SVProgressHUD dismiss];
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [tableView endRefresh];
        [SVProgressHUD dismiss];
    }];
}

- (void)chooseBrandBtnDidClick:(UIButton *)sender {
    
    NRWCarChooseBrandVC *vc = [[NRWCarChooseBrandVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    __weak typeof(chooseBrandBtn)weakBtn = chooseBrandBtn;
    
    vc.chooseBrandCompleted = ^(NSString *brandId, NSString *brandName) {
      
        _brandId = brandId;
        weakBtn.setNormalTitle(isEmptyOrNilString(brandName)? @"品牌": brandName);
        [self loadNewData];
    };
}

- (void)chooseCarBtnDidClick:(UIButton *)sender {
    
    if (isEmptyOrNilString(_brandId)) {
        
        [SVProgressHUD showErrorWithStatus:@"请先选择车辆品牌"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NRWCarChooseCarModelVC *vc = [[NRWCarChooseCarModelVC alloc] init];
    vc.carBrandId = _brandId.integerValue;
    vc.carBrandName = chooseBrandBtn.titleLabel.text;
    [self.navigationController pushViewController:vc animated:YES];
    __weak typeof(chooseCarBtn)weakBtn = chooseCarBtn;
    vc.chooseCarModelCompleted = ^(NSString *carModelId, NSString *carModelName) {
        _modelId = carModelId;
        weakBtn.setNormalTitle(isEmptyOrNilString(carModelName)? @"车型": carModelName);
        [self loadNewData];
    };
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return model.result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarMultipleChooseCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model = model.result[indexPath.row];
    
    cell.selectedState = [self.selectCarIdArrM containsObject:model.result[indexPath.row].carId];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Result *rModel = model.result[indexPath.row];
    BOOL isExist = [self.selectCarModelArrM containsObject:rModel];
    
    if (isExist == YES) {//存在, 应该取消选中状态
        
        [self.selectCarModelArrM removeObject:rModel];
        [self.selectCarIdArrM removeObject:rModel.carId];
    } else {
        
        [self.selectCarModelArrM addObject:rModel];
        [self.selectCarIdArrM addObject:rModel.carId];
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (NSMutableArray *)selectCarIdArrM {
    
    if (_selectCarIdArrM == nil) {
        _selectCarIdArrM = [NSMutableArray array];
    }
    return _selectCarIdArrM;
}

- (NSMutableArray *)selectCarModelArrM {
    
    if (_selectCarModelArrM == nil) {
        _selectCarModelArrM = [NSMutableArray array];
    }
    return _selectCarModelArrM;
}

@end
